package com.example.cloud.config;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

/**
 * 新增/修改字段自动填充。 http://mp.baomidou.com/guide/auto-fill-metainfo.html
 *
 * @author tongyufu
 * @since 2018年11月14日 下午4:33:11
 */
@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        List<String> properties = Arrays.asList(metaObject.getSetterNames());

        if (properties.contains("id") && metaObject.getValue("id") == null) {
            this.setId(metaObject);
        }
        if (properties.contains("creator") && metaObject.getValue("creator") == null) {
            metaObject.setValue("creator", "system");
        }
        if (properties.contains("modifier") && metaObject.getValue("modifier") == null) {
            metaObject.setValue("modifier", "system");
        }
        if (properties.contains("isDeleted")) {
            metaObject.setValue("isDeleted", "N");
        }
        if (properties.contains("gmtCreated")) {
            metaObject.setValue("gmtCreated", new Date());
        }
        if (properties.contains("gmtModified")) {
            metaObject.setValue("gmtModified", new Date());
        }
    }

    /**
     * 自定义生成id，这里没有真正实现。思路是根据注解获取ID的配置信息，然后生成ID
     *
     * @param metaObject 元对象
     */
    private void setId(MetaObject metaObject) {
        Class originalObjectClass = metaObject.getOriginalObject().getClass();
        KeySequence keySequence = AnnotationUtils.findAnnotation(originalObjectClass, KeySequence.class);
        if (keySequence == null) {
            return;
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        List<String> properties = Arrays.asList(metaObject.getSetterNames());

        if (properties.contains("gmtCreated")) {
            metaObject.setValue("gmtCreated", new Date());
        }
        if (properties.contains("gmtModified")) {
            metaObject.setValue("gmtModified", new Date());
        }
    }
}
